import * as vscode from 'vscode';
import { GitService } from './gitService';
import { SummaryGenerator } from './summaryGenerator';
import { SummaryViewProvider } from './summaryViewProvider';
import { AIService } from './aiService';
import { configureAI } from './commands/configureAI';

export function activate(context: vscode.ExtensionContext) {
    const gitService = new GitService();
    const summaryGenerator = new SummaryGenerator();
    const summaryViewProvider = new SummaryViewProvider(context.extensionUri);
    const aiService = new AIService();

    // Register command to generate summary from all commits
    let disposable = vscode.commands.registerCommand('gitsummary.generateSummary', async () => {
        try {
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                vscode.window.showErrorMessage("No workspace folder open");
                return;
            }

            // Show loading message
            const loadingMessage = vscode.window.setStatusBarMessage('$(sync~spin) Generating git commit summary...');
            
            // Create and show the webview panel immediately with loading state
            summaryViewProvider.showLoading();
            
            try {
                // Get git stats including commits, line stats, and contributors
                const gitStats = await gitService.getGitSummaryStats(workspaceFolder.uri.fsPath);
                
                // Generate summary with the additional stats
                const summary = await summaryGenerator.generateSummary(
                    gitStats.commits, 
                    gitStats.lineStats, 
                    gitStats.contributors
                );
                
                // Try to generate AI summary if configured
                let aiSummary: string | null = null;
                let aiError: string | null = null;
                
                try {
                    if (aiService.isConfigured()) {
                        vscode.window.setStatusBarMessage('$(sync~spin) Generating AI summary...');
                        aiSummary = await aiService.generateSummaryWithAI(gitStats.commits);
                    } else {
                        aiError = "AI is not configured. Use the 'Git Summary: Configure AI model' command to set it up.";
                    }
                } catch (error) {
                    const errorMessage = error instanceof Error ? error.message : String(error);
                    aiError = `Error generating AI summary: ${errorMessage}`;
                    vscode.window.showErrorMessage(aiError);
                    console.error('AI Summary Error:', error);
                } finally {
                    // Update the view with the complete data
                    summaryViewProvider.update(summary, aiSummary, aiError);
                }
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : String(error);
                vscode.window.showErrorMessage(`Error generating summary: ${errorMessage}`);
                summaryViewProvider.showError(`Error generating summary: ${errorMessage}`);
            } finally {
                // Always dispose the loading message
                loadingMessage.dispose();
            }
        } catch (error) {
            vscode.window.showErrorMessage(`Error generating summary: ${error}`);
        }
    });

    // Register command to generate summary with date range
    let disposableRange = vscode.commands.registerCommand('gitsummary.generateSummaryWithRange', async () => {
        try {
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                vscode.window.showErrorMessage("No workspace folder open");
                return;
            }

            // Get date range from user
            const fromDate = await vscode.window.showInputBox({
                prompt: "Enter start date (YYYY-MM-DD)",
                placeHolder: "e.g., 2023-01-01"
            });
            
            if (!fromDate) return;

            const toDate = await vscode.window.showInputBox({
                prompt: "Enter end date (YYYY-MM-DD)",
                placeHolder: "e.g., 2023-12-31"
            });
            
            if (!toDate) return;

            // Show loading message
            const loadingMessage = vscode.window.setStatusBarMessage('$(sync~spin) Generating git commit summary...');
            
            // Create and show the webview panel immediately with loading state
            summaryViewProvider.showLoading();
            
            try {
                // Get git stats including commits, line stats, and contributors for the date range
                const gitStats = await gitService.getGitSummaryStatsInRange(
                    workspaceFolder.uri.fsPath, 
                    fromDate, 
                    toDate
                );
                
                // Generate summary with the additional stats
                const summary = await summaryGenerator.generateSummary(
                    gitStats.commits, 
                    gitStats.lineStats, 
                    gitStats.contributors
                );
                
                // Try to generate AI summary if configured
                let aiSummary: string | null = null;
                let aiError: string | null = null;
                
                try {
                    if (aiService.isConfigured()) {
                        vscode.window.setStatusBarMessage('$(sync~spin) Generating AI summary...');
                        aiSummary = await aiService.generateSummaryWithAI(gitStats.commits);
                    } else {
                        aiError = "AI is not configured. Use the 'Git Summary: Configure AI model' command to set it up.";
                    }
                } catch (error) {
                    const errorMessage = error instanceof Error ? error.message : String(error);
                    aiError = `Error generating AI summary: ${errorMessage}`;
                    vscode.window.showErrorMessage(aiError);
                    console.error('AI Summary Error:', error);
                } finally {
                    // Update the view with the complete data
                    summaryViewProvider.update(summary, aiSummary, aiError);
                }
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : String(error);
                vscode.window.showErrorMessage(`Error generating summary: ${errorMessage}`);
                summaryViewProvider.showError(`Error generating summary: ${errorMessage}`);
            } finally {
                // Always dispose the loading message
                loadingMessage.dispose();
            }
        } catch (error) {
            vscode.window.showErrorMessage(`Error generating summary: ${error}`);
        }
    });

    // Register command to configure AI
    let disposableConfigAI = vscode.commands.registerCommand('gitsummary.configureAI', async () => {
        await configureAI(aiService);
    });

    context.subscriptions.push(disposable);
    context.subscriptions.push(disposableRange);
    context.subscriptions.push(disposableConfigAI);
}

export function deactivate() {}
